package com.niuke;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 62. 目录删除
 * https://blog.csdn.net/m0_46181452/article/details/131667115
 */
public class NiukeMoni62 {

    public static Map<Integer, List<Integer>> data;

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int dateCount = Integer.parseInt(scanner.nextLine());

        // 根目录id为0
        data = new HashMap<>();
        for (int i = 0; i < dateCount; i++) {
            String[] line = scanner.nextLine().split(" ");
            int value = Integer.parseInt(line[0]);
            int key = Integer.parseInt(line[1]);
            List<Integer> subDir = data.getOrDefault(key, new ArrayList<>());
            subDir.add(value);
            data.put(key, subDir);
        }

        int delete = Integer.parseInt(scanner.nextLine());

        List<Integer> keys = new ArrayList<>();
        keys.add(0);

        List<Integer> result = new ArrayList<>();
        dfs(keys, result, delete);

        result.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer integer, Integer t1) {
                return integer - t1;
            }
        });
        System.out.println(Arrays.toString(result.toArray()));
    }

    public static void dfs(List<Integer> keys, List<Integer> result, int delete) {
        if (keys == null) {
            return;
        }
        for (int i = 0; i < keys.size(); i++) {
            int key = keys.get(i);
            if (key != delete) {
                result.add(key);
                dfs(data.get(key), result, delete);
            }
        }
    }

}
